<template class="firstpage">
  <div>
    <div class="boxMargin">
      <el-tabs v-model="customData.activeName" style="width:80%;" @tab-click="handleClick">
        <el-tab-pane label="图文详情" name="first">
          <!-- 图片上传组件辅助-->
          <el-upload
            ref="upload"
            class="avatar-uploader"
            action
            name="img"
            multiple
            :show-file-list="false"
            :http-request="beforeUpload"
            accept=".png,.jpg"
          />
          <el-row style="text-align:right;margin-right: 40%;">
            <el-col><el-button type="primary" size="small" @click="getimgsrc">图片排序</el-button></el-col>
          </el-row>
          <!-- 富文本开始 -->
          <div class="edit_container" style="margin-top:10px;">
            <quill-editor ref="descInfo" v-model="customData.descInfo" class="editor editors" :options="editorOption" />
          </div>
          <!-- 富文本结束 -->
        </el-tab-pane>
      </el-tabs>
      <el-row>
        <el-col :span="24" style="text-align: center;margin-top:20px;">
          <el-button type="success" @click="infoUpdate">保存</el-button>
        </el-col>
      </el-row>
    </div>
    <el-dialog :visible.sync="dialogData.isSort" title="编辑图文详情" style="margin-top: -10vh;">
      <div style="width:100%;margin-bottom: 5px;margin-top: -20px;">
        <el-row style="line-height: 30px;">
          <el-col :span="8">当前图文详情</el-col>
          <el-col :span="8">&nbsp;</el-col>
          <el-col :span="8" style="text-align: right"><el-button style="margin-right: 20px;" type="primary" size="small" @click="getSore">确定排序</el-button></el-col>
        </el-row>
      </div>
      <div style="display:flex;flex-wrap: wrap;" class="mainImgStyle">
        <draggable v-model="customData.imgData" style="display:flex;flex-wrap: wrap;" chosen-class="chosen" force-fallback="true" group="item" animation="1000">
          <transition-group>
            <div v-for="(item,index) in customData.imgData" :key="index" class="item" style="margin:5px;">
              <div class="drawing_div" style="margin-bottom:10px;">
                <img v-if="item" :src="item.imageUrl" alt="" style="max-width:100%;max-height:100%">
              </div>
              <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ item.imageName }}</p>
              <el-button type="danger" class="buttonWidht" size="small" @click="getDelete(item,index)">删除</el-button>
            </div>
          </transition-group>
        </draggable>
        <el-upload
          ref="transparencyDrawing"
          action
          :show-file-list="false"
          :file-list="customData.uploadChineseFileList"
          :auto-upload="false"
          :multiple="true"
          :on-change="beforeUploadGet"
          accept=".png,.jpg"
        >
          <div style="margin: 5px;">
            <div class="drawing_div" style="margin: 5px;float: left"><i data-v-90c66e46="" class="el-icon-plus" /></div>
            <div style="float: left;text-align: left;">
              <p>格式：JPG，PNG</p>
              <p>大小：不超过1M</p>
            </div>
          </div>
        </el-upload>
      </div>
      <el-divider style="margin-top: -20px;" />
      <div style="width:100%;margin-bottom: 20px;">移除图文详情</div>
      <div style="display:flex;flex-wrap: wrap;">
        <div v-for="(item,index) in customData.imgRemoveData" :key="index" style="margin-right:10px;flex:none;width:136px;height:250px;">
          <div class="drawing_div" style="margin-bottom:10px;position:relative">
            <img v-if="item" :src="item.imageUrl" alt="" style="max-width:100%;max-height:100%">
          </div>
          <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ item.imageName }}</p>
          <el-button
            type="primary"
            class="buttonWidht"
            size="small"
            @click="getAdd(item, index)"
          >添加</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import $ from 'jquery'
import _validate from '../../../../../framework/commonJs/wptx_validate'
import _tools from '../../../../../framework/commonJs/wptx_tools'
import _common from '../../../../../framework/commonJs/wptx_common'
import { global } from '../../../../../filter/global-api'
// 富文本开始
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import draggable from 'vuedraggable'
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [
    {
      header: 1
    },
    {
      header: 2
    }
  ],
  [
    {
      list: 'ordered'
    },
    {
      list: 'bullet'
    }
  ],
  [
    {
      size: ['small', false, 'large', 'huge']
    }
  ],
  [
    {
      header: [1, 2, 3, 4, 5, 6, false]
    }
  ],
  [
    {
      color: []
    },
    {
      background: []
    }
  ],
  [
    {
      align: []
    }
  ],
  ['image']
]
// 富文本结束
import _api from '@/framework/API/generalItem'
const _FUNCTION_NAME = ''
export default {
  components: {
    quillEditor,
    draggable
  },
  filters: {},
  data() {
    return {
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'image': function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      editorOptionEn: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'image': function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader-en input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      tableData: [],
      searchData: {
      },
      searchDataBuffer: {
      },
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },
      dialogData: {
        isSort: false,
        isSortEn: false
      },
      historyData: {},
      infoData: {},
      customData: {
        activeName: 'first',
        descInfo: '',
        masterItemId: '',
        id: '',
        imgData: [],
        imgRemoveData: [],
        imgDataEn: [],
        imgRemoveDataEn: [],
        uploadChineseFileList: [],
        uploadEngineFileList: [],
        needUploadMainImageCount: 0,
        uploadTmpFileList: [],
        imgDescList: [
          {
            imageName: '',
            displayUrl: ''
          }
        ]
      },
      form: {
      },
      rules: {}
    }
  },
  computed: {},
  watch: {
  },
  created() { },
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
  },
  beforeDestroy() { },
  methods: {
    onInit(data) {
      const self = this
      self.customData.masterItemId = sessionStorage.getItem('itemId')
      const params = {
        masterItemId: sessionStorage.getItem('itemId')
      }
      _api.descDetail(self, params, self.callBack_descDetail)
    },
    onSearch(data) {
      const self = this
    },
    onChangePage(data) {
      const self = this
      const params = {
        masterItemId: self.customData.masterItemId
      }
      _api.descDetail(self, params, self.callBack_descDetail)
    },
    onReset(data) {
      const self = this
    },
    onAdd(data) { },
    onDelete(data) {
      const self = this
    },
    onInfo(data) {
      const self = this
    },
    onUpdate(formName) {
      const self = this
    },
    onBathDelete() {
      const self = this
    },
    onBathUpdate() { },
    onDisable(data) {
      const self = this
    },
    onEnable(data) {
      const self = this
    },
    onUpload(data) { },
    onBathUpload() { },
    onExport(data) { },
    onDownload(data) { },
    onHistory(data) { },
    callBack_descDetail(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        // _validate.openTip(self, "返回数据为空", "warning");
      } else {
        self.customData.id = data.data.id
        self.customData.descInfo = data.data.descInfo
        self.customData.imgDescList = data.data.imgDescList
        if (data.data.descInfo == undefined) {
          self.customData.descInfo = ''
        }
        if (data.data.imgDescList == undefined) {
          self.customData.imgDescList = []
        }
      }
    },
    callBack_descUpdate(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        _validate.openTip(self, '保存成功', 'success')
        self.customData.imgRemoveData = []
        self.customData.imgRemoveDataEn = []
        self.onChangePage()
      }
    },
    // 富文本插入图片前
    beforeUploadGet(file, fileList) {
      const self = this
      const extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const AllUpExt = '.png|.jpg|'
      const isLt10M = file.size / 1024 / 1024 < 1
      if (!isLt10M) {
        _validate.openTip(self, '文件大小不能超过1MB', 'warning')
        return isLt10M
      }
      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      self.uploadSuccessGet(file.raw, file.name, fileList)
      // {index: 1, length: 0}
    },
    // 上传图片成功
    uploadSuccessGet(file, name, fileList) {
      const self = this
      const quill = self.$refs.descInfo.quill
      const fd = new FormData()
      fd.append('file', file)
      fd.append('masterItemId', self.customData.masterItemId)
      fd.append('imageType', '3')
      const url = process.env.VUE_APP_IMAGE_UPLOAD
      self.customData.needUploadMainImageCount += 1
      const imgIndex = fileList.length
      const length = self.customData.descInfo.length
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        self.customData.needUploadMainImageCount -= 1
        if (res.code != 200) {
          _validate.openTip(self, name + res.message, 'error')
        } else {
          _validate.openTip(self, '图片上传成功', 'success')
          if (res.result.data) {
            if (res.result.data.uploadId != '' && res.result.data.uploadId != null) {
              const url = res.result.data.extDomain + res.result.data.imagePreview + res.result.data.uploadId
              const imageName = res.result.data.imageName
              // 调整光标到最后
              if (url != '' && url != null) {
                self.customData.uploadTmpFileList.push({
                  imgNum: imgIndex,
                  imgUrl: url,
                  imgName: imageName
                })
                if (self.customData.needUploadMainImageCount < 1) {
                  for (let i = 0; i < self.customData.uploadTmpFileList.length; i++) {
                    for (let j = 0; j < self.customData.uploadTmpFileList.length; j++) {
                      if ((self.customData.uploadTmpFileList[j].imgNum) == i + 1) {
                        self.customData.imgData.splice(self.customData.imgData.length + 1, 0, { imageUrl: self.customData.uploadTmpFileList[j].imgUrl, imageName: self.customData.uploadTmpFileList[j].imgName })
                        self.customData.imgDescList.splice(self.customData.imgDescList.length + 1, 0, { displayUrl: self.customData.uploadTmpFileList[j].imgUrl, imageName: self.customData.uploadTmpFileList[j].imgName })
                        const quillIndex = length + self.customData.imgData.length + 1
                        quill.setSelection(quillIndex)
                        quill.insertEmbed(quillIndex, 'image', self.customData.uploadTmpFileList[j].imgUrl)
                      }
                    }
                  }
                  self.customData.uploadTmpFileList = []
                  self.customData.uploadChineseFileList = []
                }
              }
            }
          }
        }
      },
      function(error) {
        self.$message.error(error)
      }
      )
    },
    // 富文本插入图片前
    beforeUpload(file) {
      const self = this
      const extName = file.file.name.substring(file.file.name.lastIndexOf('.')).toLowerCase()
      const AllUpExt = '.png|.jpg|'
      const isLt10M = file.file.size / 1024 / 1024 < 1
      if (!isLt10M) {
        _validate.openTip(self, '文件大小不能超过1MB', 'warning')
        return isLt10M
      }
      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      self.uploadSuccess(file.file, file.file.name)
    },
    uploadSuccess(file, name) {
      const self = this
      const quill = self.$refs.descInfo.quill
      const fd = new FormData()
      fd.append('file', file)
      fd.append('masterItemId', self.customData.masterItemId)
      fd.append('imageType', 3)
      const url = process.env.VUE_APP_IMAGE_UPLOAD
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        if (res.code != 200) {
          _validate.openTip(self, name + res.message, 'error')
        } else {
          _validate.openTip(self, '图片上传成功', 'success')
          if (res.result.data) {
            // 插入图片  res.info为服务器返回的图片地址
            const length = quill.getSelection().index
            // 插入图片  res.info为服务器返回的图片地址
            const url = res.result.data.displayUrl
            self.customData.imgData.splice(self.customData.imgData.length + 1, 0, { imageUrl: url, imageName: res.result.data.imageName })
            self.customData.imgDescList.splice(self.customData.imgDescList.length + 1, 0, { displayUrl: url, imageName: res.result.data.imageName })
            quill.insertEmbed(length, 'image', url)
            // 调整光标到最后
            quill.setSelection(length + 1)
          }
        }
      },
      function(error) {
        self.$message.error(error)
      }
      )
    },
    handleClick(tab) {
      const self = this
      if (tab.name == 'first') {
      } else if (tab.name == 'second') {
      }
    },
    infoUpdate() {
      const self = this
      const params = {
        id: self.customData.id ? self.customData.id : '',
        masterItemId: self.customData.masterItemId
      }
      let text = ''
      if (!_validate.checkEmpty(self.customData.descInfo)) {
        text = self.customData.descInfo
        text = text.replace(/<p>/g, '<nav>')
        text = text.replace(/<(\/)p>/g, '</nav>')
      }
      if (self.customData.activeName == 'first') {
        params.descInfo = text
        params.descInfo = text
      }
      _api.descUpdate(self, params, self.callBack_descUpdate)
    },
    getimgsrc() {
      const self = this
      const a = $('.editors .ql-editor').find('img')
      const imgUrlData = []
      self.customData.imgData = []
      let flag = true
      for (let i = 0; i < a.length; i++) {
        flag = true
        for (let j = 0; j < self.customData.imgDescList.length; j++) {
          if (a[i].src === self.customData.imgDescList[j].displayUrl) {
            imgUrlData.push(
              {
                imageUrl: a[i].src,
                imageName: self.customData.imgDescList[j].imageName
              }
            )
            flag = false
            break
          }
        }
        if (flag) {
          imgUrlData.push(
            {
              imageUrl: a[i].src
            }
          )
        }
      }
      self.customData.imgData = imgUrlData
      self.dialogData.isSort = true
    },
    getSore() {
      const self = this
      self.$nextTick(() => {
        for (let i = 0; i < self.customData.imgData.length; i++) {
          $('.editors .ql-editor').find('img').eq(i).attr('src', self.customData.imgData[i].imageUrl)
        }
        self.dialogData.isSort = false
      })
    },

    getPageCn() {
      const self = this
      self.$nextTick(() => {
        var a = $('.editors .ql-editor p').find('img')
        for (var j = 0; j < self.customData.imgData.length; j++) {
          a[j].src = self.customData.imgData[j]
        }
        self.customData.descInfo = $('.editors .ql-editor').html()
      })
    },
    getDelete(item, index) {
      const self = this
      self.$nextTick(() => {
        self.customData.imgRemoveData.splice(self.customData.imgRemoveData.length, 0, item)
        self.customData.imgData.splice(index, 1)
        const imgSrcArr = $('.editors .ql-editor').find('img')
        for (let j = 0; j < imgSrcArr.length; j++) {
          if (imgSrcArr[j].currentSrc === item.imageUrl) {
            $('.editors .ql-editor').find('img').eq(j).remove()
            break
          }
        }
      })
    },
    getAdd(item, index) {
      const self = this
      self.$nextTick(() => {
        const quill = self.$refs.descInfo.quill
        const length = self.customData.descInfo.length
        if (item != '' && item != null) {
          self.customData.imgData.splice(self.customData.imgData.length, 0, item)
          self.customData.imgRemoveData.splice(index, 1)
          quill.setSelection(length + 1)
          quill.insertEmbed(length, 'image', item.imageUrl)
        }
      })
    }
  }
}
</script>
<style scoped>
.header{
    line-height: 45px;
    font-size: 15px;
}
.quill-editor {
    /* height: 500px; */
    max-height: 600px;
    overflow-y: scroll;
}
.drawing_div{
    border-radius: 6px;
    background-color: #fbfdff;
    width:136px;
    height:136px;
    box-sizing:border-box;
    border:1px dashed #c0ccda;
    display:flex;
    justify-content: center;
    align-items: center;
}
.title{
    font-size: 15px;
}
.buttonWidht{
    width: 100%;
}
/*被拖拽对象的样式*/
.item {
    padding: 6px;
    background-color: #fdfdfd;
    border: solid 1px #eee;
    margin-bottom: 10px;
    cursor: move;
}
.previewBox span{
    display: flex; flex-wrap: wrap;
}
.mainImgStyle span{
    display: flex; flex-wrap: wrap;
}
</style>
